package com.atguigu.JVMDay02;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeUnit;

//虚引用   任何时候都有可能被回收
public class FourReferenceDemo {
    public static void main(String[] args) {
        User user = new User(20,"zs");
        //新建引用队列
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> phantomReference = new PhantomReference<>(user,referenceQueue);
        user = null;//解除强引用

        //判断虚引用对象是否被回收
        boolean isCollected = false;
        while(!isCollected){
            System.gc();
                //线程睡眠几秒
                try {
                    TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
           if(phantomReference.isEnqueued()){
               isCollected=true;
           }

        }
        System.out.println("虚引用是否被回收："+isCollected);

    }
}
